package ua.org.enginer.controls {
	
	import flash.events.Event;
	
	import mx.binding.utils.BindingUtils;
	import mx.collections.ArrayCollection;
	import mx.containers.HBox;
	import mx.containers.ViewStack;
	import mx.controls.Button;
	import mx.controls.Menu;
	import mx.controls.PopUpButton;
	import mx.controls.ToggleButtonBar;
	import mx.core.Container;
	import mx.events.ChildExistenceChangedEvent;
	import mx.events.MenuEvent;
	import mx.events.ResizeEvent;

	public class MenuButtonBar extends HBox {
		
		/**
	    * @private
	    */
	    public var buttonBar:ToggleButtonBar;
	    
		/**
	    * @private
	    */
	    protected var popupButton:PopUpButton;
	    
	    /**
	    * @private
	    */
	    protected var menubuttonbar:Menu;
		
		public function MenuButtonBar() {
			super();
			setStyle("horizontalGap", 0)
		}
		
		
		private var _splitIndex:uint = 5;
		public function set splitIndex(value:uint):void {
			_splitIndex = value;
			invalidateProperties()
		}

		public function get splitIndex():uint {
			return _splitIndex;
		}


		
		 /**
	     *  @private
	     */
		override protected function createChildren():void {
	    	super.createChildren()
	    	
	    	if (!buttonBar) {
	    		buttonBar = new ToggleButtonBar()
	    		
	    		buttonBar.setStyle("lastButtonStyleName", buttonBar.getStyle("buttonStyleName"))
	    		addChild(buttonBar)
	    	}
	    	
	    	// We create the menu once. This doesn't get shown until we click
	        // the Button. But it can get created here so we don't have
	        // to create it every time.
	        if(!menubuttonbar) {
	        	menubuttonbar = new Menu();

	        	menubuttonbar.setStyle("textAlign", "left");
	        	
	        	menubuttonbar.addEventListener(MenuEvent.ITEM_CLICK, onMenuItemClick);
	        }
	        
	        if(!popupButton) {
	        	popupButton = new PopUpButton();
	        	popupButton.popUp = menubuttonbar;
	        	popupButton.width = 18;
	        	
	        	popupButton.styleName = getStyle("popupButtonStyleName");
	        	// So now holder has 2 children: canvas and popupButton
	        	addChild(popupButton);
	        }
	        
	        invalidateSize();
	    }
	    
	    override protected function commitProperties():void {
	    	super.commitProperties()
	    	
	    	buttonBar.dataProvider = _dataProvider
	    	buttonBar.addEventListener(ChildExistenceChangedEvent.CHILD_ADD, onChildrenChange)
	    	buttonBar.addEventListener(ResizeEvent.RESIZE, hideButtons)
	    	if (_dataProvider) updateMenu()
	    }
	    
	    private var hidedButtons:Array
	    
	    protected function onChildrenChange(event:Event):void {
	    	var button:Button
	    	
	    	if (buttonBar.numChildren>splitIndex) {
	    		hidedButtons = []
		    	for(var i:int = splitIndex; i<buttonBar.numChildren; i++) {
		    		hidedButtons.push(buttonBar.getChildAt(i))
		    	}
		    }
		    hideButtons()
	    	/*
	    	if (buttonBar.numChildren>splitIndex) {
		    	buttonBar.width = 0
		    	for(var i:int = 0; i<=splitIndex; i++) {
		    		buttonBar.width += buttonBar.getChildAt(i).width
		    	}
		    }*/
	    }
	    
	    private function hideButtons(event:Event=null):void {
	    	if (hidedButtons){
	    		for each(var button:Button in hidedButtons) {
	    			button.width = 0
		    		//button.explicitWidth = 0
		    		//button.measuredWidth = 0
		    		button.visible = button.includeInLayout = false
	    		}
	    	}
	    }
	    
	    override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
	    	super.updateDisplayList(unscaledWidth, unscaledHeight)
	    	
	    	popupButton.height = buttonBar.height
	    }
	    
		private var _dataProvider:Object;
		public function set dataProvider(value:Object):void {
			_dataProvider = value;
			invalidateProperties()
		}

		public function get dataProvider():Object {
			return _dataProvider;
		}
		
		private var popupMenuDP:ArrayCollection
		/**
	    * @private
	    * 
	    * reorderTabList loops over all the tabs and makes sure that the drop-down
	    * list is correct. This should get called every time tabs are added, removed,
	    * or re-ordered. This is a public method so other SuperTabNavigators can call 
	    * this method on each other if we're dragging tabs from one SuperTabNavigator
	    * to another.
	    */
	    public function updateMenu():void {
	    	popupMenuDP = new ArrayCollection();
			
			for(var i:int=_splitIndex; i<_dataProvider.numChildren; i++) {
				var child:Container = _dataProvider.getChildAt(i) as Container;
				
				var obj:Object = new Object();
				//setting the type to an empty string bypasses a bug in MenuItemRenderer (or in 
				//DefaultDataDescriptor, depending on how you look at it). Try commenting out the
				//line and check out the menu items.
				obj.type = "";
				obj.label = (child.label != "") ? child.label : "Untitled Tab";
				obj.icon = child.icon;
				obj.index = i
				
				popupMenuDP.addItem(obj);
			}
			
			menubuttonbar.iconField="icon";
			
			menubuttonbar.dataProvider = popupMenuDP;	
			
			//we re-assign the menu to the popup button each time just to be safe to
			//ensure that the PopUpBUtton hasn't set its popUp to null, which it has a 
			//tendency to do (I think only since Flex 3)
			//fixes issue #71: http://code.google.com/p/flexlib/issues/detail?id=71
			popupButton.popUp = menubuttonbar;
			
			BindingUtils.bindProperty(popupButton, "visible", popupMenuDP, ["length"])
	    }
	    
	    private function onMenuItemClick(event:MenuEvent):void {
	    	ViewStack(dataProvider).selectedIndex = menubuttonbar.selectedItem.index
	    	//event.itemRenderer.enabled = false
	    	
	    	var button:Button
	    	button = Button(buttonBar.getChildAt(menubuttonbar.selectedItem.index))
    		
    		hidedButtons.splice(hidedButtons.indexOf(button), 1)
    		
    		button.width = button.measuredWidth
    		button.visible = button.includeInLayout = true
    		
    		popupMenuDP.removeItemAt(event.index)
    		
    		
	    }
	}
}

